package com.upcoming.common;

/**
 * 作者：tianjiayuan
 * 创建时间：2018-05-10 11:18
 * 类描述：
 * 修改人：
 * 修改时间：
 */
public class AppToken extends Token {

    private String userID;//用户ID
    private String deviceId;//绑定的设备ID

    private final static String ISSUER = "SKA_2.0";

    public final static int APPTOKEN_STORE_EXPIRES_SECOND = 60 * 60 * 24 * 30;// token有效期 30天
    public final static long APPTOKEN_STORE_EXPIRES_MILLISECOND = (long) APPTOKEN_STORE_EXPIRES_SECOND * 1000L;// token有效期 30天


    private AppToken() {
        this.setIssueTime(System.currentTimeMillis());
        this.setExpires(System.currentTimeMillis() + APPTOKEN_STORE_EXPIRES_MILLISECOND);
        this.setSignature(getUniqueID());//TODO
    }

    public static AppToken issue(final String userId, final String deviceId) {
        AppToken appToken = new AppToken();
        appToken.setIssuer(ISSUER);
        appToken.setUserID(userId);
        appToken.setDeviceId(deviceId);
        return appToken;
    }

    /**
     * 将Token转为base64编码格式
     *
     * @return
     */
    @Override
    public String toBase64Encode() {
        StringBuffer input = new StringBuffer();
        input.append("{");
        input.append("\"userID\"").append(":\"").append(getUserID()).append("\",");
        input.append("\"expire\"").append(":").append(getExpires()).append(",");
        input.append("\"issueTime\"").append(":").append(getIssueTime()).append(",");
        input.append("\"issuer\"").append(":\"").append(getIssuer()).append("\",");
        input.append("\"signature\"").append(":\"").append(getSignature()).append("\",");
        input.append("\"deviceId\"").append(":\"").append(getDeviceId()).append("\"");
        input.append("}");

        return new sun.misc.BASE64Encoder().encode(input.toString().getBytes()).replaceAll("(?:\r\n|\n\r|\n|\r)", "");
    }

    public String getUserID() {
        return userID;
    }

    public void setUserID(String userID) {
        this.userID = userID;
    }

    public String getDeviceId() {
        return deviceId;
    }

    public void setDeviceId(String deviceId) {
        this.deviceId = deviceId;
    }
}
